#include "recovery/Topic.h"

#include "recovery/log/FileLog.h"
#include <iostream>

namespace recovery {

TopicOption::TopicOption()
: logSuffix("log")
, directory(".")
{
}

TopicOption::~TopicOption(){
}

Topic::Topic(const std::string & name, const TopicOption & option)
: name(name)
, _option(option)
, opened(false)
{
}

Topic::~Topic(){
	close();
}

int Topic::open() {
	if(!opened){
        //1.log open
        log.reset(new ::recovery::log::FileLog(name + "." + _option.logSuffix, _option.directory));
        int ret = log->open();
        if(ret != 0){
            return ret;
        }
		//TODO:
		opened = true;
		return 0;
	}
	return -1;
}
int Topic::close() {
	if(opened){
        int ret = log->close();
        if(ret != 0) return ret;
		//TODO:
		opened = false;
	}
	return 0;
}

//append the key/value -> to log & 
Topic & Topic::set(const std::string & key, const std::string & value){
    int ret = log->append(key + ":" + value + "|");
    if(ret < 0) {
        //TODO: error info from log ???
        std::cerr<< "set:append failed" << std::endl;
    }
	//TODO:
	return *this;
}
Topic & Topic::begin() {
    int ret = log->append("begin|");
    if(ret < 0){
        std::cerr << "begin:append log failed"  << std::endl;
    }
	//TODO:
	return *this;
}
Topic & Topic::commit() {
    int ret = log->append("commit|;");
    if(ret < 0){
        std::cerr << "commit:append log failed"  << std::endl;
    }
	//TODO:
	return *this;
}
Topic & Topic::rollback() {
    int ret = log->append("rollback|;");
    if(ret < 0){
        std::cerr << "rollback:append log failed"  << std::endl;
    }
	//TODO:
	return *this;
}
int Topic::visit(const std::function<int (const std::string & , const std::string &)> & fn) {
	//TODO:
	return 0;
}

}// end of namespace recovery
